package com.bzkj.web.controller.storage;

import com.bzkj.basicinfo.domain.warehouse.PdaWarehouseInBillsDetail;
import com.bzkj.basicinfo.domain.warehouse.PdaWarehouseInBillsList;
import com.bzkj.basicinfo.service.warehouse.IPdaWarehouseInBillsService;

import com.bzkj.common.annotation.Log;
import com.bzkj.common.annotation.LogB;
import com.bzkj.common.core.controller.BaseController;
import com.bzkj.common.core.domain.AjaxResult;
import com.bzkj.common.core.page.TableDataInfo;
import com.bzkj.common.enums.BusinessType;
import com.bzkj.common.utils.poi.ExcelUtil;
import com.bzkj.common.utils.SecurityUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 入库单据管理Controller
 *
 * @author system
 * @date 2025-10-17
 */
@RestController
@RequestMapping("/storage/buyStore")
public class BuyStoreController extends BaseController {

    @Resource
    private IPdaWarehouseInBillsService pdaWarehouseInBillsService;

    /**
     * 查询入库单据列表
     */
    //@PreAuthorize("@ss.hasPermi('storage:buyStore:list')")
    @GetMapping("/list")
    public TableDataInfo list(@RequestParam(required = false) String orderStatus, 
                             @RequestParam(required = false) String optType, 
                             @RequestParam(required = false) String orderNo,
                             @RequestParam(required = false) String supplierName,
                             @RequestParam(required = false) String beginTime,
                             @RequestParam(required = false) String endTime,
                              @RequestParam(required = false) String type) {
        startPage();

        PdaWarehouseInBillsList billsList = new PdaWarehouseInBillsList();

        // 处理前端传入的参数
            if("0".equals(type)){//收货管理页面
                if(orderStatus.equals("all")){
                    billsList.setBillsState("0,1,4,5");
                }else{
                    billsList.setBillsState(orderStatus);
                }
            }else if("1".equals(type)){//验收管理页面
                if(orderStatus.equals("all")){
                billsList.setBillsState("1,2,4,5");
                }else{
                    billsList.setBillsState(orderStatus);
                }
            }else if("2".equals(type)){//上架管理页面
                if(orderStatus.equals("all")) {
                    billsList.setBillsState("2,3,4,5");
                }else{
                    billsList.setBillsState(orderStatus);
                }
            }else{
                return new TableDataInfo();
            }

        // optType: -1表示全部, 其他值表示具体类型
        if (optType != null && !"-1".equals(optType)) {
            billsList.setBillsType(optType);
        }

        // orderNo: 入库单号
        if (orderNo != null && !orderNo.isEmpty()) {
            billsList.setBillsId(orderNo);
        }
        
        // supplierName: 往来单位名称（需要在实体类和Mapper中支持）
        if (supplierName != null && !supplierName.isEmpty()) {
            billsList.setBillsCdName(supplierName);
        }
        
        // beginTime和endTime: 制单时间范围（需要在实体类和Mapper中支持）
        if (beginTime != null && !beginTime.isEmpty()) {
            billsList.setBeginTime(beginTime);
        }
        
        if (endTime != null && !endTime.isEmpty()) {
            billsList.setEndTime(endTime);
        }

        List<PdaWarehouseInBillsList> list = pdaWarehouseInBillsService.selectPdaWarehouseInBillsList(billsList);
        return getDataTable(list);
    }

    /**
     * 确认收货
     */
    @PreAuthorize("@ss.hasPermi('warehouse:pda:receive')")
    @LogB(title = "确认收货", businessType = BusinessType.OTHER)
    @PostMapping("/receive")
    public AjaxResult confirmReceive(@RequestBody ReceiveRequest request) {
        String receiverUserId = SecurityUtils.getUsername();
        String receiverUserName = SecurityUtils.getLoginUser().getUser().getNickName();

        return pdaWarehouseInBillsService.confirmReceiveWithBatch(
                request.getBillsId(),
                request.getDetailList(),
                receiverUserId,
                receiverUserName
        );
    }

    /**
     * 作废操作
     */
    @Log(title = "入库单据-作废", businessType = BusinessType.UPDATE)
    @PostMapping("/cancel/{billsID}")
    public AjaxResult cancelBills(@PathVariable String billsID, @RequestBody CancelRequest cancelRequest) {
        return toAjax(pdaWarehouseInBillsService.cancelBills(billsID, cancelRequest.getReason()));
    }


    /**
     * 收货拒收
     * 状态从0（未收货）变为4（异常）
     */
    @PreAuthorize("@ss.hasPermi('warehouse:pda:receive:reject')")
    @LogB(title = "收货拒收", businessType = BusinessType.UPDATE)
    @PostMapping("/receive/reject")
    public AjaxResult rejectReceive(@RequestBody RejectRequest request) {
        String rejectUserId = SecurityUtils.getUsername();
        String rejectUserName = SecurityUtils.getLoginUser().getUser().getNickName();

        return pdaWarehouseInBillsService.rejectReceive(
                request.getBillsId(),
                request.getRejectReason(),
                rejectUserId,
                rejectUserName
        );
    }

    /**
     * 确认验收
     * 状态从1（已到货待验收）变为2（验收完成待上架）
     */
    @PreAuthorize("@ss.hasPermi('warehouse:pda:inspect:accept')")
    @LogB(title = "确认验收", businessType = BusinessType.UPDATE)
    @PostMapping("/inspect/accept")
    public AjaxResult inspectGoods(@RequestBody InspectRequest request) {
        String acceptUserId = SecurityUtils.getUsername();
        String acceptUserName = SecurityUtils.getLoginUser().getUser().getNickName();

        return pdaWarehouseInBillsService.inspectGoods(
                request.getBillsId(),
                request.getDetailList(),
                acceptUserId,
                acceptUserName
        );
    }

    /**
     * 验收拒收
     * 状态从1（已到货待验收）变为4（异常）
     */
    @PreAuthorize("@ss.hasPermi('warehouse:pda:inspect:reject')")
    @LogB(title = "验收拒收", businessType = BusinessType.UPDATE)
    @PostMapping("/inspect/reject")
    public AjaxResult rejectInspect(@RequestBody RejectRequest request) {
        String acceptUserId = SecurityUtils.getUsername();
        String acceptUserName = SecurityUtils.getLoginUser().getUser().getNickName();

        return pdaWarehouseInBillsService.rejectInspect(
                request.getBillsId(),
                request.getRejectReason(),
                acceptUserId,
                acceptUserName
        );
    }

    /**
     * 执行上架（调用pdaGrounding，自动完成库存入库操作）
     * 状态从2（验收完成待上架）变为3（已上架）
     * 功能：
     * 1. 更新主表状态为已上架（状态3）
     * 2. 自动保存库存到 wms_sto_stock 表
     * 3. 自动插入库存记录到 wms_sto_stock_log 表
     */
    @PreAuthorize("@ss.hasPermi('warehouse:pda:shelving:accept')")
    @LogB(title = "执行上架", businessType = BusinessType.UPDATE)
    @PostMapping("/shelving/accept")
    public AjaxResult shelvingGoods(@RequestBody ShelvingRequest request) {
        try {
            // 直接调用pdaGrounding方法，内部会自动处理库存
            int result = pdaWarehouseInBillsService.pdaGrounding(request.getBillsId());
            return result > 0 ? AjaxResult.success("上架成功，库存已同步") : AjaxResult.error("上架失败");
        } catch (Exception e) {
            return AjaxResult.error("上架失败：" + e.getMessage());
        }
    }

    /**
     * 上架异常
     * 状态从2（验收完成待上架）变为4（异常）
     */
    @PreAuthorize("@ss.hasPermi('warehouse:pda:shelving:exception')")
    @LogB(title = "上架异常", businessType = BusinessType.UPDATE)
    @PostMapping("/shelving/exception")
    public AjaxResult shelvingException(@RequestBody ExceptionRequest request) {
        String shelvingUserId = SecurityUtils.getUsername();
        String shelvingUserName = SecurityUtils.getLoginUser().getUser().getNickName();

        return pdaWarehouseInBillsService.shelvingException(
                request.getBillsId(),
                request.getExceptionReason(),
                shelvingUserId,
                shelvingUserName
        );
    }
    /**
     * 导出入库单据列表
     */
    //@PreAuthorize("@ss.hasPermi('storage:buyStore:export')")
    @Log(title = "入库单据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PdaWarehouseInBillsList billsList) {
        List<PdaWarehouseInBillsList> list = pdaWarehouseInBillsService.selectPdaWarehouseInBillsList(billsList);
        ExcelUtil<PdaWarehouseInBillsList> util = new ExcelUtil<PdaWarehouseInBillsList>(PdaWarehouseInBillsList.class);
        util.exportExcel(response, list, "入库单据数据");
    }

    /**
     * 获取入库单据详细信息
     */
    @GetMapping(value = "/{billsID}")
    public AjaxResult getInfo(@PathVariable("billsID") String billsID) {
        return success(pdaWarehouseInBillsService.selectPdaWarehouseInBillsByBillsID(billsID));
    }

    /**
     * 新增入库单据
     */
    @Log(title = "入库单据", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PdaWarehouseInBillsList billsList) {
        return toAjax(pdaWarehouseInBillsService.insertPdaWarehouseInBillsList(billsList));
    }

    /**
     * 修改入库单据
     */
    //@PreAuthorize("@ss.hasPermi('storage:buyStore:edit')")
    @Log(title = "入库单据", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PdaWarehouseInBillsList billsList) {
        return toAjax(pdaWarehouseInBillsService.updatePdaWarehouseInBillsList(billsList));
    }

    /**
     * 删除入库单据
     */
    @Log(title = "入库单据", businessType = BusinessType.DELETE)
    @DeleteMapping("/{billsIDs}")
    public AjaxResult remove(@PathVariable String[] billsIDs) {
        return toAjax(pdaWarehouseInBillsService.deletePdaWarehouseInBillsByBillsIDs(billsIDs));
    }

    /**
     * 拒收请求
     */
    public static class RejectRequest {
        private String billsId;
        private String rejectReason;

        public String getBillsId() {
            return billsId;
        }

        public void setBillsId(String billsId) {
            this.billsId = billsId;
        }

        public String getRejectReason() {
            return rejectReason;
        }

        public void setRejectReason(String rejectReason) {
            this.rejectReason = rejectReason;
        }
    }

    /**
     * 作废请求参数
     */
    public static class CancelRequest {
        private String reason;

        public String getReason() {
            return reason;
        }

        public void setReason(String reason) {
            this.reason = reason;
        }
    }
    /**
     * 收货请求
     */
    public static class ReceiveRequest {
        private String billsId;
        private List<PdaWarehouseInBillsDetail> detailList;

        public String getBillsId() {
            return billsId;
        }

        public void setBillsId(String billsId) {
            this.billsId = billsId;
        }

        public List<PdaWarehouseInBillsDetail> getDetailList() {
            return detailList;
        }

        public void setDetailList(List<PdaWarehouseInBillsDetail> detailList) {
            this.detailList = detailList;
        }
    }
    /**
     * 验收请求
     */
    public static class InspectRequest {
        private String billsId;
        private List<PdaWarehouseInBillsDetail> detailList;

        public String getBillsId() {
            return billsId;
        }

        public void setBillsId(String billsId) {
            this.billsId = billsId;
        }

        public List<PdaWarehouseInBillsDetail> getDetailList() {
            return detailList;
        }

        public void setDetailList(List<PdaWarehouseInBillsDetail> detailList) {
            this.detailList = detailList;
        }
    }
    /**
     * 上架请求
     */
    public static class ShelvingRequest {
        private String billsId;
        private List<PdaWarehouseInBillsDetail> detailList;

        public String getBillsId() {
            return billsId;
        }

        public void setBillsId(String billsId) {
            this.billsId = billsId;
        }

        public List<PdaWarehouseInBillsDetail> getDetailList() {
            return detailList;
        }

        public void setDetailList(List<PdaWarehouseInBillsDetail> detailList) {
            this.detailList = detailList;
        }
    }
    /**
     * 异常请求
     */
    public static class ExceptionRequest {
        private String billsId;
        private String exceptionReason;

        public String getBillsId() {
            return billsId;
        }

        public void setBillsId(String billsId) {
            this.billsId = billsId;
        }

        public String getExceptionReason() {
            return exceptionReason;
        }

        public void setExceptionReason(String exceptionReason) {
            this.exceptionReason = exceptionReason;
        }
    }
}

